# 当前的命令调用flask要和web主程序分离，管理员偶尔会用到，用户不会用到
from flask import Flask, flash, jsonify, Response, render_template, request, session, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
import os
from os.path import join, dirname, realpath
from configparser import ConfigParser
from sqlalchemy.sql import text
import json
from datetime import datetime
import time

app = Flask(__name__)

current_file_path = os.path.abspath(__file__)
ROOT_PATH = os.path.dirname(os.path.dirname(current_file_path))
print(ROOT_PATH)
# 创建解析器对象
config = ConfigParser()
# 读取INI文件
config.read(ROOT_PATH + '\\config.ini')

# 数据库配置读取
DATABASE_HOST = config.get('database', 'host', fallback='127.0.0.1')
DATABASE_PORT = config.getint('database', 'port', fallback=3306)
DATABASE_USERNAME = config.get('database', 'username', fallback='root')
DATABASE_PASSWORD = config.get('database', 'password', fallback='root')
DATABASE_NAME = config.get('database', 'name', fallback='flask_admin')
# 通过修改以下代码来操作不同的SQL比写原生SQL简单很多 --》通过ORM可以实现从底层更改使用的SQL
SQLALCHEMY_DATABASE_URI = f"mysql+pymysql://{DATABASE_USERNAME}:{DATABASE_PASSWORD}@{DATABASE_HOST}:{DATABASE_PORT}/{DATABASE_NAME}?charset=utf8mb4"

app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
# 是否追踪数据库修改，一般不开启, 会影响性能
# app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# 是否显示底层执行的SQL语句
# app.config['SQLALCHEMY_ECHO'] = True
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

db = SQLAlchemy(app)

# db.create_all()

# with app.test_request_context():
# # 执行原生SQL语句, 测试下能不能查询到结果
#     result = db.session.execute(text('select *  from  fa_admin'))
#     print(result.fetchall())

# 读取json
json_file = ROOT_PATH + '\\static\\admin\\api\\menus.json'
# 打开JSON文件并读取其内容
with open(json_file, 'r', encoding='utf-8') as f:
    data = json.load(f)

value_sql = ''
if data['code'] is 0:
    # 打印读取到的数据
    for item in data['data']:
        dt_obj = datetime.strptime(item['createTime'], '%Y/%m/%d %H:%M:%S')
        timestamp = dt_obj.timestamp()

        # if item['menuUrl'] is None or item['menuUrl'] is '':
        #     item['menuUrl'] = 'null'

        # if item['authority'] is None or item['authority'] is '':
        #     item['authority'] = 'null'

        value_sql += "(%d,'%s','%s','%s','%s',%d,%d,%d,%d,%d)," % (
            item['authorityId'],
            item['authorityName'],
            item['menuUrl'],
            item['menuIcon'],
            item['authority'],
            item['checked'],
            item['isMenu'],
            item['orderNumber'],
            item['parentId'],
            timestamp
        )
        # print(item['authorityName'])
print(value_sql)

insert_sql = f'INSERT INTO fa_menu(id,name,url,icon,authority,checked,is_menu,sort,parent_id,createtime) VALUE {value_sql}'
with app.test_request_context():
    # 执行原生SQL语句, 测试下能不能查询到结果
    result = db.session.execute(text(insert_sql))
    print(result.fetchall())

# if __name__ == '__main__':
# app.run()
